export const toNumber = (value: unknown, fallback = 0): number => {
  const num = Number(value);
  return Number.isFinite(num) ? num : fallback;
};

export const ensureArray = <T>(value: unknown): Array<T> => {
  if (Array.isArray(value)) return value as Array<T>;
  if (value === undefined || value === null) return [];
  return [value as T];
};

export interface PaginationInput {
  total?: number | string;
  page?: number | string;
  page_size?: number | string;
  pageSize?: number | string;
  current_page?: number | string;
  currentPage?: number | string;
}

export const normalisePagination = (
  input: PaginationInput | undefined,
  fallbackPage: number,
  fallbackSize: number,
  fallbackTotal: number
) => {
  const total = toNumber(
    input?.total ?? (input as any)?.count ?? fallbackTotal,
    fallbackTotal
  );
  const pageSize = toNumber(input?.page_size ?? input?.pageSize, fallbackSize);
  const currentPage = toNumber(
    input?.page ?? input?.current_page ?? input?.currentPage,
    fallbackPage
  );

  return {
    total,
    pageSize,
    currentPage
  };
};
